<template>
  <div class="organization">
    <div class="organization-left">
      <ButtonGroup
        :hasPermiAdd="['system:organization:add']"
        :hasPermiEdit="['system:organization:edit']"
        :hasPermiDelete="['system:organization:delete']"
        @add="onAdd"
        @edit="onEdit"
        @delete="onDelete"
      ></ButtonGroup>
      <WebsiteTree
        ref="websiteTree"
        :cus-height="40"
        @handleNodeClick="handleNodeClick"
      ></WebsiteTree>
    </div>
    <div class="organization-right">
      <MyForm
        v-model:formData="formData"
        v-model:columns="formColumns"
        :rules="rules"
        :porpModel="true"
        background="#fff"
        labelWidth="120"
        :saveBtnLoading="saveBtnLoading"
        :formDisabled="formStatus === 'view'"
        :loading="loading"
        :isCalculateLayout="true"
        @submit="onSubmit"
      >
      </MyForm>
    </div>
    <Add
      v-if="dialogVisible"
      v-model:visible="dialogVisible"
      :currRow="currRow"
      :isType="isType"
      @onSubmit="onAddSubmit"
    ></Add>
  </div>
</template>

<script lang="tsx" setup>
import { ref, onMounted, watch } from "vue";
import * as api from "@/api/index.js";
import { columnFilters, getSubZhEn } from "@/utils/mUtils.js";
import i18n from "@/lang/index.js";
import { ElMessage, ElMessageBox } from "element-plus";
import Add from "./components/add.vue";
const formData = ref({
  siteRankCode: "",
  sysSiteBankList: [],
});
const rules = ref({
  siteName: {
    required: true,
    message: "请输入机构名称",
    trigger: ["blur", "change"],
  },
  siteCode: {
    required: true,
    message: "请输入组别编号",
    trigger: ["blur", "change"],
  },
  siteNameChinese: {
    required: true,
    message: "请输入组别名称",
    trigger: ["blur", "change"],
  },
  siteRankCode: {
    required: true,
    message: "请选择机构级别",
    trigger: "change",
  },
});
const formStatus = ref("view");
const loading = ref(false);
const formColumns = ref([
  {
    title: "组织架构",
    structure: [
      {
        title: "",
        content: [
          {
            x: 0,
            y: 0,
            w: 8,
            h: 1,
            i: "1",
            label: "机构编码",
            prop: "siteCode",
            type: "label_input",
            span: 8,
            maxlength: 30,
            disabled: formStatus.value !== "add",
          },
          {
            label: "国家/省/市/区",
            propSelectCode: "countryCode",
            propSelectName: "countryName",
            propSelectAdd: "countryAdd",
            prop: "provinceCityArea",
            type: "label_province_city_area",
            propSelectOptions: [],
            propSelectPlaceholder: "国家",
            propsSelect: {
              value: "countryCode",
              label: "countryName",
              keyAdd: "countryAdd",
            },
            parmasKey: {
              provinceName: "provinceName",
              provinceCode: "provinceCode",
              cityName: "cityName",
              cityCode: "cityCode",
              areaName: "areaName",
              areaCode: "areaCode",
            },
            options: [],
            props: {
              value: "areaCode",
              label: "areaName",
              children: "children",
            },
            placeholder: "省/市/区(县)",
            span: 8,
            x: 8,
            y: 0,
            w: 8,
            h: 1,
            i: "2",
            onCascaderChange: (argeObj) => {
              formData.value = { ...formData.value, ...argeObj };
            },
          },
          {
            type: "label_input",
            label: "上级机构",
            prop: "parentName",
            disabled: true,
            span: 8,
            x: 16,
            y: 0,
            w: 8,
            h: 1,
            i: "3",
          },
          {
            label: "机构名称(中)",
            prop: "siteName",
            type: "label_input",
            span: 8,
            maxlength: 100,
            x: 0,
            y: 1,
            w: 8,
            h: 1,
            i: "4",
          },
          {
            label: "详细地址(中)",
            prop: "address",
            type: "label_input",
            maxlength: 500,
            span: 16,
            x: 8,
            y: 1,
            w: 16,
            h: 1,
            i: "5",
          },
          {
            label: "机构名称(英)",
            prop: "siteNameEn",
            type: "label_input",
            span: 8,
            maxlength: 100,
            x: 0,
            y: 2,
            w: 8,
            h: 1,
            i: "6",
          },

          {
            label: "详细地址(英)",
            prop: "addressEn",
            type: "label_input",
            maxlength: 500,
            span: 16,
            x: 8,
            y: 2,
            w: 16,
            h: 1,
            i: "7",
          },
          {
            label: "机构级别",
            prop: "siteRankCode",
            name: "siteRankName",
            type: "label_select",
            options: [],
            props: {
              value: "subCode",
              label: "subName",
            },
            placeholder: i18n.global.t("请选择机构级别"),
            span: 8,
            x: 0,
            y: 3,
            w: 8,
            h: 1,
            i: "8",
          },

          {
            label: "是否启用",
            prop: "status",
            type: "label_switch",
            activeValue: "1",
            inactiveValue: "0",
            span: 8,
            x: 8,
            y: 3,
            w: 8,
            h: 1,
            i: "9",
          },
        ],
      },
    ],
  },
  {
    title: "银行信息",
    structure: [
      {
        type: "tabel",
        tableIndex: 0,
        prop: "sysSiteBankList",
        hasPermiAdd: ["system:organization:bankAdd"],
        hasPermiDelete: ["system:organization:bankDelete"],
        columns: [
          {
            type: "checkbox",
            width: 50,
            fixed: "left",
            align: "center",
          },
          {
            field: "bankName",
            title: "开户行名称(中)",
            slots: {
              default: ({ row }) => {
                return [
                  <el-button
                    type="primary"
                    disabled={formStatus.value === "view"}
                    link
                    onClick={() => {
                      onBankNameClick(row);
                    }}
                  >
                    {row.bankName || "-"}
                  </el-button>,
                ];
              },
            },
          },
          {
            field: "bankNameEn",
            title: "开户行名称(英)",
          },
          {
            field: "address",
            title: "开户行地址(中)",
          },
          {
            field: "addressEn",
            title: "开户行地址(英)",
          },
          {
            field: "swiftCode",
            title: "国际代码",
          },
          {
            field: "sysSiteBankAccountList",
            title: "银行账户",
            listKey: "account",
            formatter: ({ row }) => {
              return (
                row.sysSiteBankAccountList?.length &&
                row.sysSiteBankAccountList
                  .map((item) => {
                    return item.account;
                  })
                  .join(",")
              );
            },
          },
        ],
        multipleSelection: [],
        buttonType: ["add", "delete"],
        batchDelete: true,
        onAdd: (black) => {
          dialogVisible.value = true;
          isType.value = "add";
          currRow.value = {
            sysSiteBankAccountList: [],
            siteCode: formData.value.siteCode,
          };
        },
      },
    ],
    hide: false,
  },
]);
const currentSite = ref(null);

const treeDate = ref([]);
const saveBtnLoading = ref(false);
const websiteTree = ref();
const dialogVisible = ref(false);
const currRow = ref(null);
const isType = ref("add");
onMounted(() => {
  getSub();
  getCountryList();
});
watch(
  () => formData.value.siteRankCode,
  (val) => {
    if (val !== "001003") {
      formColumns.value[1].hide = false;
    } else {
      formColumns.value[1].hide = true;
    }
  },
  {
    immediate: true,
  }
);
watch(
  () => formStatus.value,
  (val) => {
    if (val) {
      columnFilters(formColumns.value, "siteCode").disabled = val !== "add";
    }
  }
);
const onEdit = (row) => {
  formStatus.value = "edit";
};
const onDelete = (row) => {
  ElMessageBox.confirm(i18n.global.t("确认删除吗？"), i18n.global.t("提示"), {
    confirmButtonText: i18n.global.t("确定"),
    cancelButtonText: i18n.global.t("取消"),
    type: "warning",
  }).then(async () => {
    await api.default.system.organization.delete(currentSite.value.id);
    websiteTree.value.getWebsiteData();
    ElMessage.success("删除成功");
    formData.value = {};
    currentSite.value = null;
  });
};
const getCountryList = async () => {
  const { rows } = await api.default.system.provinceCityArea.countryList({
    pageSize: 300,
    enableFlag: "1",
  });
  const treeData = rows.map((item) => ({
    ...item,
    label: i18n.global.t(item.countryName),
  }));
  columnFilters(formColumns.value, "provinceCityArea").propSelectOptions =
    treeData;
};
const getSub = () => {
  getSubZhEn({
    code: "001",
  }).then((res) => {
    columnFilters(formColumns.value, "siteRankCode").options = res["001"];
  });
};
const onSubmit = async () => {
  saveBtnLoading.value = true;
  try {
    const sysSiteBankList = formData.value.sysSiteBankList.map((item) => {
      return item;
    });
    const params = {
      ...formData.value,
      sysSiteBankList,
    };
    if (formStatus.value === "add") {
      await api.default.system.organization.add(params);
      ElMessage.success("新增成功");
    } else {
      await api.default.system.organization.edit(params);
      ElMessage.success("修改成功");
    }
    websiteTree.value.getWebsiteData();
    saveBtnLoading.value = false;
  } catch (err) {
    saveBtnLoading.value = false;
  }
};
const handleNodeClick = (row) => {
  currentSite.value = { ...row };
  getInfoData();
  formStatus.value = "view";
};
const getInfoData = async () => {
  loading.value = true;
  try {
    const res = await api.default.system.organization.getInfo(
      currentSite.value.id
    );
    formData.value = {
      ...res.data,
      sysSiteBankList: res.data.sysSiteBankList || [],
      provinceCityArea: [
        res.data.provinceCode,
        res.data.cityCode,
        res.data.areaCode,
      ],
    };
  } finally {
    loading.value = false;
  }
};
const onAdd = () => {
  formStatus.value = "add";
  if (currentSite) {
    formData.value = {
      parentId: currentSite.value.id,
      parentName: currentSite.value.name,
      sysSiteBankList: [],
      status: "1",
    };
  }
};
const onBankNameClick = (row) => {
  isType.value = "edit";
  dialogVisible.value = true;
  currRow.value = {
    ...row,
    sysSiteBankAccountList: row.sysSiteBankAccountList || [],
  };
};
const onAddSubmit = (val) => {
  dialogVisible.value = false;
  if (isType.value === "edit") {
    formData.value.sysSiteBankList = formData.value.sysSiteBankList.map(
      (item) => {
        if (item.id === val.id) return val;
        return item;
      }
    );
    return;
  }
  formData.value.sysSiteBankList.push(val);
};
</script>

<style lang="scss" scoped>
.organization {
  width: 100%;
  height: 100%;
  display: flex;
  padding: 10px 0;
  .organization-left {
    width: 350px;
    padding: 10px;
    height: 100%;
    background: #fff;
  }
  .organization-right {
    // margin-left: 10px;
    width: calc(100% - 350px);
    background: #fff;
    padding: 20px;
  }
}
</style>